package org.linlinjava.litemall.admin.web;

import com.github.pagehelper.PageInfo;
import org.linlinjava.litemall.admin.annotation.LoginAdmin;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallBrandNew;
import org.linlinjava.litemall.db.service.LitemallNewBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 品牌商
 *
 * @author zhy
 * @date 2019-07-22 19:04
 **/
@RestController
@RequestMapping("/admin/newBrand")
public class AdminNewBrandController {
	@Autowired
	private LitemallNewBrandService newBrandService;

	@GetMapping("/list")
	public Object list(@LoginAdmin Integer adminId,
		String id, String name,
		@RequestParam(value = "page", defaultValue = "1") Integer page,
		@RequestParam(value = "limit", defaultValue = "10") Integer limit,
		String sort, String order){
		if(adminId == null){
			return ResponseUtil.unlogin();
		}

		List<LitemallBrandNew> brandList = newBrandService.querySelective(id, name, page, limit, sort, order);
		long total = PageInfo.of(brandList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", brandList);

		return ResponseUtil.ok(data);
	}

	@GetMapping("/totalList")
	public Object totalList(@LoginAdmin Integer adminId,
		String id, String name,
		String sort, String order){

		List<LitemallBrandNew> brandList = newBrandService.queryTotalSelective(id, name, sort, order);

		Map<String, Object> data = new HashMap<>();
		data.put("items", brandList);

		return ResponseUtil.ok(data);
	}

	@PostMapping("/create")
	public Object create(@LoginAdmin Integer adminId, @RequestBody LitemallBrandNew brand){
		if(adminId == null){
			return ResponseUtil.unlogin();
		}
		brand.setAddTime(LocalDateTime.now());
		newBrandService.add(brand);
		return ResponseUtil.ok(brand);
	}

	@GetMapping("/read")
	public Object read(@LoginAdmin Integer adminId, Integer id){
		if(adminId == null){
			return ResponseUtil.unlogin();
		}

		if(id == null){
			return ResponseUtil.badArgument();
		}

		LitemallBrandNew brand = newBrandService.findById(id);
		return ResponseUtil.ok(brand);
	}

	@PostMapping("/update")
	public Object update(@LoginAdmin Integer adminId, @RequestBody LitemallBrandNew brand){
		if(adminId == null){
			return ResponseUtil.unlogin();
		}
		newBrandService.updateById(brand);
		return ResponseUtil.ok(brand);
	}

	@PostMapping("/delete")
	public Object delete(@LoginAdmin Integer adminId, @RequestBody LitemallBrandNew brand){
		if(adminId == null){
			return ResponseUtil.unlogin();
		}
		newBrandService.deleteById(brand.getId());
		return ResponseUtil.ok();
	}
}
